﻿using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using RotovapPlatform.Domain.Business.Machine.Entities;

namespace RotovapPlatform.UI.ViewModels.DeviceMaintenance
{
	/// <summary>
	/// 优先级枚举
	/// </summary>
	public enum Priority
	{
		Low,
		Medium,
		High
	}

	/// <summary>
	/// 设备维护提醒视图模型
	/// </summary>
	public partial class MaintenanceReminderViewModel : ObservableObject
	{
		private readonly ILogger<MaintenanceReminderViewModel> _logger;

		/// <summary>
		/// 维护提醒列表
		/// </summary>
		[ObservableProperty]
		private ObservableCollection<MaintenanceReminder> _reminders = new ObservableCollection<MaintenanceReminder>();

		/// <summary>
		/// 选中的维护提醒
		/// </summary>
		[ObservableProperty]
		private MaintenanceReminder _selectedReminder;

		/// <summary>
		/// 是否显示已完成的提醒
		/// </summary>
		[ObservableProperty]
		private bool _showCompleted;

		/// <summary>
		/// 是否显示添加/编辑对话框
		/// </summary>
		[ObservableProperty]
		private bool _isDialogOpen;



		/// <summary>
		/// 是否处于编辑模式
		/// </summary>
		[ObservableProperty]
		private bool _isEditMode;

		/// <summary>
		/// 对话框标题
		/// </summary>
		[ObservableProperty]
		private string _dialogTitle = "添加维护提醒";

		/// <summary>
		/// 编辑中的维护提醒
		/// </summary>
		[ObservableProperty]
		private MaintenanceReminder _editingReminder = new MaintenanceReminder();

		/// <summary>
		/// 设备组件列表
		/// </summary>
		[ObservableProperty]
		private ObservableCollection<string> _deviceComponents = new ObservableCollection<string>();

		/// <summary>
		/// 维护类型列表
		/// </summary>
		[ObservableProperty]
		private ObservableCollection<string> _maintenanceTypes = new ObservableCollection<string>();

		///// <summary>
		///// 构造函数
		///// </summary>
		///// <param name="logger">日志记录器</param>
		//public MaintenanceReminderViewModel(ILogger<MaintenanceReminderViewModel> logger)
		//{
		//	_logger = logger;
		//	_logger.LogInformation("设备维护提醒视图模型已初始化");

		//	// 初始化命令
		//	AddReminderCommand = new RelayCommand(OpenAddDialog);
		//	EditReminderCommand = new RelayCommand<MaintenanceReminder>(OpenEditDialog);
		//	SaveReminderCommand = new RelayCommand(async () => await SaveReminderAsync());
		//	CancelDialogCommand = new RelayCommand(CloseDialog);
		//	MarkAsCompletedCommand = new RelayCommand<MaintenanceReminder>(async (reminder) => await MarkAsCompletedAsync(reminder));
		//	DeleteReminderCommand = new RelayCommand<MaintenanceReminder>(async (reminder) => await DeleteReminderAsync(reminder));
		//	RefreshCommand = new RelayCommand(async () => await LoadRemindersAsync());
		//}

		/// <summary>
		/// 添加提醒命令
		/// </summary>
		public ICommand AddReminderCommand { get; }

		/// <summary>
		/// 编辑提醒命令
		/// </summary>
		public ICommand EditReminderCommand { get; }

		/// <summary>
		/// 保存提醒命令
		/// </summary>
		public ICommand SaveReminderCommand { get; }

		/// <summary>
		/// 取消对话框命令
		/// </summary>
		public ICommand CancelDialogCommand { get; }

		/// <summary>
		/// 标记为已完成命令
		/// </summary>
		public ICommand MarkAsCompletedCommand { get; }

		/// <summary>
		/// 删除提醒命令
		/// </summary>
		public ICommand DeleteReminderCommand { get; }

		/// <summary>
		/// 刷新命令
		/// </summary>
		public ICommand RefreshCommand { get; }

		/// <summary>
		/// 初始化
		/// </summary>
		//public async Task InitializeAsync()
		//{
		//	try
		//	{
		//		IsLoading = true;
		//		_logger.LogInformation("正在初始化设备维护提醒...");

		//		// 初始化设备组件列表
		//		DeviceComponents.Clear();
		//		DeviceComponents.Add("旋转电机");
		//		DeviceComponents.Add("加热浴");
		//		DeviceComponents.Add("冷凝器");
		//		DeviceComponents.Add("真空泵");
		//		DeviceComponents.Add("密封圈");
		//		DeviceComponents.Add("控制系统");
		//		DeviceComponents.Add("传感器");
		//		DeviceComponents.Add("阀门");

		//		// 初始化维护类型列表
		//		MaintenanceTypes.Clear();
		//		MaintenanceTypes.Add("定期检查");
		//		MaintenanceTypes.Add("清洁");
		//		MaintenanceTypes.Add("更换零件");
		//		MaintenanceTypes.Add("校准");
		//		MaintenanceTypes.Add("润滑");
		//		MaintenanceTypes.Add("软件更新");

		//		// 加载提醒列表
		//		await LoadRemindersAsync();

		//		_logger.LogInformation("设备维护提醒初始化完成");
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, "初始化设备维护提醒时发生错误");
		//	}
		//	finally
		//	{
		//		IsLoading = false;
		//	}
		//}

		///// <summary>
		///// 加载提醒列表
		///// </summary>
		//private async Task LoadRemindersAsync()
		//{
		//	try
		//	{
		//		IsLoading = true;
		//		_logger.LogInformation("正在加载维护提醒列表...");

		//		// 这里将来会添加实际的数据加载逻辑
		//		await Task.Delay(500); // 模拟加载延迟

		//		// 清空现有数据
		//		Reminders.Clear();

		//		// 模拟添加一些提醒数据
		//		var random = new Random();
		//		var now = DateTime.Now;

		//		for (int i = 0; i < 10; i++)
		//		{
		//			var dueDate = now.AddDays(random.Next(-10, 30));
		//			var isCompleted = dueDate < now && random.Next(2) == 0;
		//			var component = DeviceComponents[random.Next(DeviceComponents.Count)];
		//			var maintenanceType = MaintenanceTypes[random.Next(MaintenanceTypes.Count)];

		//			// 如果设置为不显示已完成的提醒，且当前提醒已完成，则跳过
		//			if (!ShowCompleted && isCompleted)
		//			{
		//				continue;
		//			}

		//			Reminders.Add(new MaintenanceReminder
		//			{
		//				Id = i + 1,
		//				Title = $"{component} {maintenanceType}",
		//				Description = $"对{component}进行{maintenanceType}，确保设备正常运行。",
		//				DeviceComponent = component,
		//				MaintenanceType = maintenanceType,
		//				DueDate = dueDate,
		//				Priority = (Priority)random.Next(3),
		//				IsCompleted = isCompleted,
		//				CompletionDate = isCompleted ? dueDate.AddDays(random.Next(-5, 2)) : null,
		//				CompletedBy = isCompleted ? $"用户{random.Next(1, 5)}" : null,
		//				Notes = isCompleted ? "维护已完成，设备运行正常。" : null
		//			});
		//		}

		//		_logger.LogInformation($"已加载 {Reminders.Count} 个维护提醒");
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, "加载维护提醒列表时发生错误");
		//	}
		//	finally
		//	{
		//		IsLoading = false;
		//	}
		//}

		///// <summary>
		///// 打开添加对话框
		///// </summary>
		//private void OpenAddDialog()
		//{
		//	try
		//	{
		//		_logger.LogInformation("打开添加维护提醒对话框");

		//		IsEditMode = false;
		//		DialogTitle = "添加维护提醒";
		//		EditingReminder = new MaintenanceReminder
		//		{
		//			DueDate = DateTime.Now.AddDays(7),
		//			Priority = Priority.Medium
		//		};
		//		IsDialogOpen = true;
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, "打开添加维护提醒对话框时发生错误");
		//	}
		//}

		///// <summary>
		///// 打开编辑对话框
		///// </summary>
		//private void OpenEditDialog(MaintenanceReminder reminder)
		//{
		//	try
		//	{
		//		if (reminder == null)
		//		{
		//			return;
		//		}

		//		_logger.LogInformation($"打开编辑维护提醒对话框，ID: {reminder.Id}");

		//		IsEditMode = true;
		//		DialogTitle = "编辑维护提醒";
		//		EditingReminder = new MaintenanceReminder
		//		{
		//			Id = reminder.Id,
		//			Title = reminder.Title,
		//			Description = reminder.Description,
		//			DeviceComponent = reminder.DeviceComponent,
		//			MaintenanceType = reminder.MaintenanceType,
		//			DueDate = reminder.DueDate,
		//			Priority = reminder.Priority,
		//			IsCompleted = reminder.IsCompleted,
		//			CompletionDate = reminder.CompletionDate,
		//			CompletedBy = reminder.CompletedBy,
		//			Notes = reminder.Notes
		//		};
		//		IsDialogOpen = true;
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, $"打开编辑维护提醒对话框时发生错误，ID: {reminder?.Id}");
		//	}
		//}

		///// <summary>
		///// 关闭对话框
		///// </summary>
		//private void CloseDialog()
		//{
		//	IsDialogOpen = false;
		//}

		///// <summary>
		///// 保存提醒
		///// </summary>
		//private async Task SaveReminderAsync()
		//{
		//	try
		//	{
		//		_logger.LogInformation($"正在保存维护提醒，ID: {EditingReminder.Id}");

		//		// 这里将来会添加实际的保存逻辑
		//		await Task.Delay(500); // 模拟保存延迟

		//		if (IsEditMode)
		//		{
		//			// 更新现有提醒
		//			var existingReminder = Reminders.FirstOrDefault(r => r.Id == EditingReminder.Id);
		//			if (existingReminder != null)
		//			{
		//				var index = Reminders.IndexOf(existingReminder);
		//				Reminders[index] = EditingReminder;
		//			}
		//		}
		//		else
		//		{
		//			// 添加新提醒
		//			EditingReminder.Id = Reminders.Count > 0 ? Reminders.Max(r => r.Id) + 1 : 1;
		//			Reminders.Add(EditingReminder);
		//		}

		//		// 关闭对话框
		//		IsDialogOpen = false;

		//		_logger.LogInformation($"维护提醒保存成功，ID: {EditingReminder.Id}");
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, $"保存维护提醒时发生错误，ID: {EditingReminder.Id}");
		//	}
		//}

		///// <summary>
		///// 标记为已完成
		///// </summary>
		//private async Task MarkAsCompletedAsync(MaintenanceReminder reminder)
		//{
		//	try
		//	{
		//		if (reminder == null)
		//		{
		//			return;
		//		}

		//		_logger.LogInformation($"正在标记维护提醒为已完成，ID: {reminder.Id}");

		//		// 这里将来会添加实际的标记逻辑
		//		await Task.Delay(500); // 模拟操作延迟

		//		// 更新提醒状态
		//		reminder.IsCompleted = true;
		//		reminder.CompletionDate = DateTime.Now;
		//		reminder.CompletedBy = "当前用户"; // 这里将来会使用实际的用户信息

		//		// 如果设置为不显示已完成的提醒，则从列表中移除
		//		if (!ShowCompleted)
		//		{
		//			Reminders.Remove(reminder);
		//		}

		//		_logger.LogInformation($"维护提醒已标记为已完成，ID: {reminder.Id}");
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, $"标记维护提醒为已完成时发生错误，ID: {reminder?.Id}");
		//	}
		//}

		///// <summary>
		///// 删除提醒
		///// </summary>
		//private async Task DeleteReminderAsync(MaintenanceReminder reminder)
		//{
		//	try
		//	{
		//		if (reminder == null)
		//		{
		//			return;
		//		}

		//		_logger.LogInformation($"正在删除维护提醒，ID: {reminder.Id}");

		//		// 这里将来会添加实际的删除逻辑
		//		await Task.Delay(500); // 模拟操作延迟

		//		// 从列表中移除
		//		Reminders.Remove(reminder);

		//		_logger.LogInformation($"维护提醒删除成功，ID: {reminder.Id}");
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.LogError(ex, $"删除维护提醒时发生错误，ID: {reminder?.Id}");
		//	}
		//}

		///// <summary>
		///// 显示已完成提醒状态变化
		///// </summary>
		//partial void OnShowCompletedChanged(bool value)
		//{
		//	_ = LoadRemindersAsync();
		//}
	}

	/// <summary>
	/// 维护提醒类
	/// </summary>
	public class MaintenanceReminder
	{
		/// <summary>
		/// ID
		/// </summary>
		public int Id { get; set; }

		/// <summary>
		/// 标题
		/// </summary>
		public string Title { get; set; }

		/// <summary>
		/// 描述
		/// </summary>
		public string Description { get; set; }

		/// <summary>
		/// 设备组件
		/// </summary>
		public string DeviceComponent { get; set; }

		/// <summary>
		/// 维护类型
		/// </summary>
		public string MaintenanceType { get; set; }

		/// <summary>
		/// 到期日期
		/// </summary>
		public DateTime DueDate { get; set; }

		/// <summary>
		/// 优先级
		/// </summary>
		public Priority Priority { get; set; }

		/// <summary>
		/// 是否已完成
		/// </summary>
		public bool IsCompleted { get; set; }

		/// <summary>
		/// 完成日期
		/// </summary>
		public DateTime? CompletionDate { get; set; }

		/// <summary>
		/// 完成人
		/// </summary>
		public string CompletedBy { get; set; }

		/// <summary>
		/// 备注
		/// </summary>
		public string Notes { get; set; }

		/// <summary>
		/// 是否逾期
		/// </summary>
		public bool IsOverdue => !IsCompleted && DueDate < DateTime.Now;

		/// <summary>
		/// 状态文本
		/// </summary>
		public string StatusText => IsCompleted ? "已完成" : (IsOverdue ? "已逾期" : "待处理");
	}
}